<template>
  <!--    <page-layout :title="description">-->
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="付款单号" style="margin-bottom: 10px;">
              <a-input placeholder="付款单号" v-model="queryParam.invoiceNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="结算单位" style="margin-bottom: 10px;">
              <a-select v-model="queryParam.settlementCompany" allowClear showSearch style="width: 100%"
                        placeholder="请选择结算单位">
                <a-select-option v-for="(item, key) in companyData" :key="key" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="申请人" style="margin-bottom: 10px;">
              <a-input placeholder="申请人" v-model="queryParam.paySerial"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="开票状态" style="margin-bottom: 10px;">
              <j-dict-select-tag v-model="queryParam.billStatus" placeholder="请选择发票状态" dictCode="kp_status" />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">

            <a-form-item label="申请日期" style="margin-bottom:10px;">
              <a-form-item
                :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }"
              >
                <a-date-picker style="width: 100%" v-model="queryParam.createDateStart" valueFormat="YYYY-MM-DD" />
              </a-form-item>
              <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">-</span>
              <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
                <a-date-picker style="width: 100%" v-model="queryParam.createDateEnd" valueFormat="YYYY-MM-DD" />
              </a-form-item>
            </a-form-item>
          </a-col>
          <!--          </template>-->
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <span style="width: 100%" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <a-spin :spinning="confirmLoading"
            style="min-height: 400px !important;">
      <a-button style="margin-bottom: 10px;" @click="showCreateApply(1)" type="primary" ghost icon="plus">
        付款申请（海运）
      </a-button>
      <a-button v-has="'fk:xm'" style="margin-bottom: 10px;margin-left: 8px;" @click="showCreateApply(2)" icon="plus">
        付款申请（箱贸）
      </a-button>
      <a-table
        ref="table"
        :scroll="{x:1500,y:400}"
        size="small"
        bordered
        rowKey="id"
        :columns="columns"
        :components="components"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="confirmLoading"
        class="j-table-force-nowrap">
        <span slot="paySerial" slot-scope="text, record">
          <a @click="showdetail(record)">{{ text }}</a>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="showdetail(record)">详情</a>
          <template v-if="(record.status==1 || record.status==3)&& !isDisabledAuth('fk:check')">
            <a-divider type="vertical" />
            <a @click="showedit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗？" @confirm="() => deleteRow(record.id)">
                  <a>删除</a>
            </a-popconfirm>
          </template>
          <template v-if="(record.status==1 || record.status==2)&& isDisabledAuth('fk:check')">
           <a-divider type="vertical" />
           <a-dropdown :trigger="['click']">
              <a class="ant-dropdown-link" @click="e => e.preventDefault()" v-if="record.status==1">
                审核 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="0" v-if="record.status==1">
                  <a-popconfirm title="确定通过吗？" @confirm="() => actionRow(record.id,1)">
                    <a>通过</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item key="1" v-if="record.status==1">
                  <a-popconfirm title="确定驳回吗？" @confirm="() => actionRow(record.id,2)">
                    <a>驳回</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item key="2" v-if="record.status==2">
                  <a-popconfirm title="确定撤销吗？" @confirm="() => actionRow(record.id,3)">
                    <a>撤销</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
    </span>
      </a-table>


    </a-spin>

    <PayApplyDetail v-if="payDetailVisible" ref="payDetailVisibleDrawer" @close="close"
    ></PayApplyDetail>
    <PayApply v-if="payAppVisible" ref="payAppVisibleDrawer" @close="close" @gotoAdd="gotoAdd"
    ></PayApply>

    <PayAddFee v-if="payAddFeeVisible" ref="payAddFeeVisibleDrawer" @close="addPageClose"
               @selectrow="selectrow"></PayAddFee>
    <PayAddFeeTrade v-if="payAddFeeTradeVisible" @selectrow="selectrow" ref="payAddFeeTradeDrawer"
                    @close="addPageClose"></PayAddFeeTrade>
  </a-card>

</template>

<script>
import '@/assets/less/TableExpand.less'
import JDate from '@/components/jeecg/JDate.vue'
import PageLayout from '@/components/page/PageLayout'
import Vue from 'vue'
import PayAddFee from './PayAddFee'
import PayApply from './PayApply'
import PayApplyDetail from './PayApplyDetail'
import { getAction, deleteAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import PayAddFeeTrade from '@views/payManage/PayAddFeeTrade'

export default {
  name: 'invoiceInfo',
  mixins: [JeecgListMixin],
  components: {
    PayAddFeeTrade,
    JDate,
    PageLayout,
    PayAddFee,
    PayApply,
    PayApplyDetail
  },
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props
          const col = this.columns.find(col => {
            const k = col.dataIndex || col.key
            return k === key
          })

          if (!col || !col.width) {
            return h('th', { ...restProps }, [...children])
          }

          const dragProps = {
            key: col.dataIndex || col.key,
            class: 'table-draggable-handle',
            attrs: {
              w: 10,
              x: col.width,
              z: 1,
              axis: 'x',
              draggable: true,
              resizable: false
            },
            on: {
              dragging: (x, y) => {
                col.width = Math.max(x, 1)
              }
            }
          }
          const drag = h('vue-draggable-resizable', { ...dragProps })
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag])
        }
      }
    }
    return {
      status: 0,
      feeStatus: 1,
      companyData: [],
      payAppVisible: false,
      payDetailVisible: false,
      payAddFeeVisible: false,
      payAddFeeTradeVisible: false,
      confirmLoading: false,
      //列设置
      settingColumns: [],
      columns: [],
      // 表头
      defColumns: [
        {
          title: '#',
          dataIndex: 'rowIndex',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          fixed: 'left',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '付款状态',
          dataIndex: 'status',
          width: 100,
          customRender: function(t, r, index) {
            if (t == 1) {
              return '付款申请中'
            } else if (t == 2) {
              return '审核通过'
            } else if (t == 3) {
              return '驳回申请'
            } else if (t == 4) {
              return '核销完成'
            } else if (t == 5) {
              return '部分核销'
            }
          }
        },
        {
          title: '付款单号',
          dataIndex: 'paySerial',
          width: 200,
          scopedSlots: { customRender: 'paySerial' }
        },
        {
          title: '结算单位',
          dataIndex: 'settlementCompany',
          width: 260
        }, {
          title: '付款币种',
          dataIndex: 'currency',
          width: 100
        },
        {
          title: '付款金额',
          dataIndex: 'amount',
          width: 100
        },
        {
          title: '付款汇率',
          dataIndex: 'rate',
          width: 80
        },
        {
          title: '本位币金额',
          dataIndex: 'cnyAmount',
          width: 100
        },
        {
          title: '付款类型',
          dataIndex: 'payType',
          width: 100
        },
        {
          title: '开票状态',
          dataIndex: 'billStatus',
          width: 120
        },
        {
          title: '申请人',
          dataIndex: 'createBy',
          width: 70
        },
        {
          title: '申请日期',
          dataIndex: 'createTime',
          width: 100
        },
        {
          title: '审核人',
          dataIndex: 'checkUser',
          width: 70
        },
        {
          title: '审核日期',
          dataIndex: 'checkDate',
          width: 100
        },
        {
          title: '申请事由',
          dataIndex: 'applyReason',
          width: 200
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 200
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 230,
          fixed: 'right',
          align: 'left',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 选择的行
      selectedRows: [],
      url: {
        list: '/payapply/init/list',
        deleteRow: '/payapply/delete',
        tjshRow: '/invoice/action/submit',
        rejectRow: '/payapply/action/reject',
        revokeRow: '/payapply/action/revoke',
        approvedRow: '/payapply/action/approved'

      },
      dictOptions: {},
      selectid: '',
      payType: 1
    }
  },
  created() {
    this.loading = true
    this.initDict()
    // this.searchQuery()
    this.initColumns()
  },
  computed: {
    // importExcelUrl: function(){
    //   return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    // },
  },
  methods: {
    initDict() {
      let param = { isLock: 0, pageSize: 99999 }
      getAction('/fee/list', param).then(res => {
        console.log(res.result.records)
        let feeData = []
        for (let i = 0; i < res.result.records.length; i++) {
          feeData.push({
            value: res.result.records[i].feeName,
            text: res.result.records[i].feeName
          })
        }
        this.feeNameData = feeData
      })
      getAction('/companydata/list', param).then(res => {
        console.log(res.result.records)
        let companyDataList = []
        for (let i = 0; i < res.result.records.length; i++) {
          companyDataList.push({
            value: res.result.records[i].companyName,
            text: res.result.records[i].companyName
          })
        }
        this.companyData = companyDataList
      })

      if (this.isDisabledAuth('fk:check') == false && this.isDisabledAuth('fk:xm')) {
        this.queryParam.so = 1
      } else if (this.isDisabledAuth('fk:xm') == false) {
        this.queryParam.so = 2
      }
    },
    showCreateApply(type) {
      this.payAppVisible = true
      this.payType = type
      this.$nextTick(() => {
        this.$refs.payAppVisibleDrawer.payApplyBuisType = type
      })
    },

    gotoAdd(val) {
      if (this.payType == 1) {
        this.payAddFeeVisible = true
        this.$nextTick(() => {
          this.$refs.payAddFeeVisibleDrawer.requestRecord(val)
        })
      } else if (this.payType == 2) {
        this.payAddFeeTradeVisible = true
        this.$nextTick(() => {
          this.$refs.payAddFeeTradeDrawer.requestRecord(val)
        })
      }

    },
    selectrow(val) {
      if (this.payType == 1) {
        this.$nextTick(() => {
          this.$refs.payAppVisibleDrawer.requestRecord(val)
        })
      } else if (this.payType == 2) {
        this.$nextTick(() => {
          this.$refs.payAppVisibleDrawer.requestRecord(val)
        })
      }
      this.addPageClose()
    },
    addPageClose() {
      if (this.payType == 1) {
        this.payAddFeeVisible = false
      } else if (this.payType == 2) {
        this.payAddFeeTradeVisible = false
      }
    },
    showdetail(val) {
      console.log(val)
      this.payDetailVisible = true
      this.$nextTick(() => {
        this.$refs.payDetailVisibleDrawer.requestRecord(val)
      })
    },
    showedit(val) {
      this.payAppVisible = true
      this.$nextTick(() => {
        this.$refs.payAppVisibleDrawer.editAction(val)
      })
    },
    close() {
      this.payAppVisible = false
      this.payDetailVisible = false
      this.loadData(1)
    },
    allOk() {
    },
    // searchQuery() {
    //   let param = {}
    //   getAction('/invoice/list', param).then((res) => {
    //     console.log(res)
    //     this.receivableList = res.result
    //   })
    // },
    //删除
    deleteRow(val) {
      let param = { id: val }
      deleteAction(this.url.deleteRow, param).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loadData(1)
      })
    },
    //提交审核
    actionRow(val, index) {
      let param = { id: val }
      let actionurl = ''
      //1审核通过 2驳回
      if (index == 1) {
        actionurl = this.url.approvedRow
      } else if (index == 2) {
        actionurl = this.url.rejectRow
      } else if (index == 3) {
        actionurl = this.url.revokeRow
      }
      postAction(actionurl, param).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loadData(1)
      })
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    isDisabledAuth(code) {
      let allAuthList = JSON.parse(sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH') || '[]')
      let isHas = false
      for (let i = 0; i < allAuthList.length; i++) {
        if (code == allAuthList[i].action) {
          isHas = true
          break
        }
      }
      return isHas
    }

  }
}
</script>
<style>
.ant-table {
  min-height: 400px !important;
}

.ant-empty-normal {
  margin: 140px 0 !important;
}
</style>
<style lang="less">

.resize-table-th {
  position: relative;

  .table-draggable-handle {
    transform: none !important;
    position: absolute;
    height: 100% !important;
    bottom: 0;
    left: auto !important;
    right: -5px;
    cursor: col-resize;
    touch-action: none;
  }

  .table-color-dust {
    background-color: #F5222D;
  }
}
</style>
